var express = require('express');
var router = express.Router();
// 加密解密
const crypto = require('crypto');
const jwt = require("jsonwebtoken");
// node自带模块
const fs = require('fs');
const formidable = require('formidable');

// 导入sql函数
const sql = require("../utils/sql");
//建立schema模型
// var mongoose = require("../mongodb/connect");
// var Goods = mongoose.model("student",{name:String,age:Number},"student");
// 引入schema
const {
  Vuer,
  Goodlist,
  Cartinfo,
  Addressinfo,
  Cityinfo,
  Coupon,
  Order
} = require('../mongodb/schema.js');

// 全局的user, token验证解析回调里的code写入
var oUser = {};


/**
 * @api {get} /hybrid/uni/goodlist 商品列表接口
 * @apiDescription 商品列表接口
 * @apiGroup goods
 * @apiParam itemType || null
 * @apiName 商品列表
 * @apiSampleRequest /hybrid/uni/goodlist
 * @apiVersion 1.0.0
 */
router.get("/goodlist", (req, res) => {
  let itemType = req.query.itemType; // 前端已做处理
  if (itemType) {
    // 具体类型
    Goodlist.find({
      itemType
    }, { _id: 0, __v: 0 }).then(result => {
      res.json({
        code: 200,
        status: 0,
        msg: "获取商品列表成功!",
        result
      })
    }).catch(() => {
      res.json({
        code: 200,
        status: -1,
        msg: "获取商品列表失败",
        result: null
      })
    })
  } else {
    // 全部
    Goodlist.find({}, { _id: 0, __v: 0 }).then(result => {
      res.json({
        code: 200,
        status: 0,
        msg: "获取商品列表成功!",
        result
      })
    }).catch(() => {
      res.json({
        code: 200,
        status: -1,
        msg: "获取商品列表失败",
        result: null
      })
    })
  }
})

/**
 * @api {get} /hybrid/uni/details 商品详情接口
 * @apiDescription 商品详情接口
 * @apiGroup goods
 * @apiParam tradeItemId
 * @apiName 商品详情
 * @apiSampleRequest /hybrid/uni/details
 * @apiVersion 1.0.0
 */
router.get("/details", (req, res) => {
  let tradeItemId = req.query.tradeItemId;
  Goodlist.findOne({
    goods_id: tradeItemId
  }, { _id: 0, __v: 0 }).then(result => {
    // console.log(result)
    if (result) {
      res.json({
        code: 200,
        status: 0,
        msg: "获取商品详情成功!",
        result
      })
    }
  }).catch(() => {
    res.json({
      code: 200,
      status: -1,
      msg: "获取商品详情失败",
      result: null
    })
  })
})

//可以拦截这个中间件`之后`所有的请求
router.use(function (req, res, next) {
  // startsWith相当于不等于
  if (!req.url.startsWith("/users/login") && req.url !== "/users/reg") {
    // jwt插件验证(退出登录: 清了服务端session和token没用,最好是前端清除后不带-也可以实现记住状态功能)
    jwt.verify(req.headers.accesstoken, "uni-app", (err, code) => {
      oUser = code
      if (!err) {
        next();
      }
      else {
        res.json({
          // 401 - Unauthorized - 请求要求用户的身份认证
          code: 401,
          status: -1,
          msg: '身份验证失败,请重新登录',
          result: null
        })
      }
    })
  } else {
    // 登录和注册(跳过检验token)可以正常访问接口
    next();
  }
})

/**
 * @api {post} /hybrid/uni/userinfo 获取用户信息接口
 * @apiDescription 获取用户信息接口
 * @apiGroup users
 * @apiName userinfo
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "获取用户信息成功",
    result: response[0]
  })
 * @apiSampleRequest /uni/userinfo
 * @apiVersion 1.0.0
 */
router.post('/userinfo', (req, res) => {
  // 参数是验证token得到的解码后的手机号
  sql.find(Vuer, { userid: oUser.userid }, { _id: 0, _v: 0 }).then((response) => {
    res.json({
      code: 200,
      status: 0,
      msg: "获取用户信息成功",
      result: response[0]
    })
  })
})

/**
 * @api {post} /hybrid/uni/modify-pwd 修改密码接口
 * @apiDescription 修改密码接口
 * @apiGroup users
 * @apiName modify-pwd
 * @apiParam { String } oldPassword 旧密码
 * @apiParam { String } password 新密码
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改密码成功",
    result: response[0]
  })
  res.json({
    code: 200,
    status: -1,
    msg: '修改失败',
    result: null
  })
 * @apiSampleRequest /uni/modify-pwd
 * @apiVersion 1.0.0
 */
router.post("/modify-pwd", (req, res) => {
  const { oldPassword, password } = req.body
  const hash = crypto.createHmac('sha256', oldPassword)
    .update('hybrid')
    .digest('hex');
  const newHash = crypto.createHmac('sha256', password)
    .update('hybrid')
    .digest('hex');
  Vuer.findOne({ userid: oUser.userid, password: hash }, { _id: 0, __v: 0 }).then(response => {
    if (response.userid === oUser.userid) {
      Vuer.updateOne({ userid: oUser.userid, password: hash }, {
        $set: {
          password: newHash
        }
      }).then(result => {
        res.json({
          code: 200,
          status: 0,
          msg: '修改成功',
          result
        })
      })
    } else {
      res({
        code: 200,
        status: -1,
        msg: '原密码有误',
        result: null
      })
    }
  })
})

/**
 * @api {post} /hybrid/uni/upload-avatar 上传头像接口
 * @apiDescription 上传头像接口- { Binary } 图片
 * @apiGroup users
 * @apiName upload-img
 * @apiParam AnyBuffer(二进制Binary)
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改头像成功",
    result: files.file.name // 返回值带上路径和名字,而public是静态目录省略
   })
 * @apiSampleRequest /uni/upload-avatar
 * @apiVersion 1.0.0
 */
router.post("/upload-avatar", (req, res) => {
  const form = formidable({ multiples: false });
  //设置上传路径
  // form.uploadDir = `./public/avatar/${oUser.userid}/`
  // NOTE: 上传不能省略`public`, 而且后面不能直接添加新的文件夹(不会自动创建)
  form.uploadDir = `./public/hy-assets/avatar/`
  form.parse(req, (err, fields, files) => {
    if (!files.file) return;  //没有上传文件，不进行任何处理
    //上传文件重命名
    fs.renameSync(files.file.path, form.uploadDir + files.file.name);
    // 更新数据库
    Vuer.updateOne({ userid: oUser.userid }, {
      $set: {
        avatar: `/hy-assets/avatar/` + files.file.name
      }
    }).then(art => {
      res.json({
        code: 200,
        status: 0,
        msg: "修改头像成功",
        result: files.file.name
      })
    })
  });
})

/**
 * @api {post} /hybrid/uni/upload-bg 上传头像接口
 * @apiDescription 上传头像接口- { Binary } 图片
 * @apiGroup users
 * @apiName upload-img
 * @apiParam AnyBuffer(二进制Binary)
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改背景成功",
    result: files.file.name // 返回值带上路径和名字,而public是静态目录省略
   })
 * @apiSampleRequest /uni/upload-bg
 * @apiVersion 1.0.0
 */
router.post("/upload-bg", (req, res) => {
  const form = formidable({ multiples: false });
  //设置上传路径
  form.uploadDir = `./public/hy-assets/bg/`
  form.parse(req, (err, fields, files) => {
    if (!files.file) return;  //没有上传文件，不进行任何处理
    //上传文件重命名
    fs.renameSync(files.file.path, form.uploadDir + files.file.name);
    // 更新数据库
    Vuer.updateOne({ userid: oUser.userid }, {
      $set: {
        poster: `/hy-assets/bg/` + files.file.name
      }
    }).then(art => {
      res.json({
        code: 200,
        status: 0,
        msg: "修改背景成功",
        result: files.file.name
      })
    })
  });
})

// TODO: 获取头像 - 没必要(直接上传之后重新请求下userinfo)
/*
router.post("/getavatar", (req, res) => {
  getusername = aesDecrypt(req.body.token, keys);
  Vuer.findOne({ username: getusername }).then(result => {
      if (!!result.avatar) {
          // console.log(result);
          res.json({
              code: 200,
              status: 0,
              msg: "头像获取成功",
              avatar: result.avatar,
          })
      } else {
          res.json({
              code: 200,
              status: -1,
              msg: "头像获取失败",
              avatar: null
          })
      }
  })
})*/


/********************* */

/**
 * @api {post} /hybrid/uni/comment-blog 评论-接口
 * @apiDescription 评论-接口
 * @apiGroup others
 * @apiName comment-blog
 * @apiParam AnyBuffer(二进制Binary)
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改成功",
    result: Array
   })
 * @apiSampleRequest /uni/comment-blog
 * @apiVersion 1.0.0
 */
router.post("/comment-blog", (req, res) => {
  console.log(req.body.id)
  console.log(req.body.commentList)
  Article.updateOne({ _id: req.body.id }, {
    $set: {
      commentNum: req.body.commentList
    }
  }).then(list => {
    if (list.nModified) {
      Article.find({}, { _id: 0, __v: 0 }).then(result => {
        if (result.length > 0) {
          res.json({
            code: 200,
            masg: '获取全部文章',
            result
          })
        } else {
          res.json({
            code: 200,
            masg: '暂无文章',
            result
          })
        }
      })
    }
  })
});



/**
 * @api {post} /hybrid/uni/support-blog 点赞-接口
 * @apiDescription 点赞-接口
 * @apiGroup others
 * @apiName support-blog
 * @apiParam AnyBuffer(二进制Binary)
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改头像成功",
    result: Array
   })
 * @apiSampleRequest /uni/support-blog
 * @apiVersion 1.0.0
 */
router.post("/support-blog", (req, res) => {
  const data = req.body
  Article.updateOne({ _id: data.id }, {
    $set: {
      praisePoints: data.praisePoints
    }
  }).then(support => {
    if (support.nModified) {
      Article.find({}, { _id: 0, __v: 0 }).then(result => {
        if (result.length > 0) {
          res.json({
            code: 200,
            masg: '获取全部文章',
            result
          })
        } else {
          res.json({
            code: 200,
            masg: '暂无文章',
            result
          })
        }
      })
    }
  })
});


/**
 * @api {post} /hybrid/uni/collect-blog 收藏-接口
 * @apiDescription 收藏-接口
 * @apiGroup others
 * @apiName collect-blog
 * @apiParam AnyBuffer(二进制Binary)
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改头像成功",
    result: Array
   })
 * @apiSampleRequest /uni/collect-blog
 * @apiVersion 1.0.0
 */
router.post("/collect-user", (req, res) => {
  const data = req.body
  Userinfo.updateOne({ token: req.headers.token }, {
    $set: {
      collectList: data.collectList
    }
  }).then(list => {
    if (list.nModified) {
      Userinfo.findOne({ token: req.headers.token }, { _id: 0, __v: 0 }).then(result => {
        res.json({
          code: 200,
          msg: '修改收藏',
          result
        })
      })
    }
  })
});




/**
 * @api {post} /hybrid/uni/addcart 加入购物车接口
 * @apiDescription 加入购物车接口
 * @apiGroup cart
 * @apiName addcart
 * @apiParam info(加入购物车的具体信息)
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "加入购物车成功",
    result: string
   })
 * @apiSampleRequest /uni/addcart
 * @apiVersion 1.0.0
 */
router.post("/addcart", (req, res) => {
  // Cartinfo
  const info = req.body.info
  const userid = oUser.userid
  // 得到tree的参数
  Goodlist.findOne({ goods_id: info.goodsId }, { _id: 0, __v: 0 }).then(good => {
    function search(sType, sVal) {
      const arr_k_s = good.sku.tree.filter(tree_k_s => {
        return tree_k_s.k_s === sType
      })
      const arr_v = arr_k_s[0].v.filter(tree_v => {
        return tree_v.id === sVal
      })
      return arr_v[0].name
    }
    const obj = { userid, ...info, selectedId: info.selectedSkuComb.id, s1: search('s1', info.selectedSkuComb.s1), s2: search('s2', info.selectedSkuComb.s2), goods_info: good.goods_info }
    // 添加或更新
    Cartinfo.findOne({ userid, goodsId: obj.goodsId, selectedId: obj.selectedId }, { _id: 0, __v: 0 }).then(result => {
      if (result) {
        // 更新
        Cartinfo.updateOne({
          userid: result.userid,
          goodsId: result.goodsId,
          selectedId: result.selectedId
        }, {
          $set: {
            selectedNum: result.selectedNum * 1 + obj.selectedNum * 1
          }
        }).then(updateres => {
          // {n: 1, nModified: 1, ok: 1 }
          if (updateres.nModified === 1) {
            res.json({
              code: 200,
              status: 0,
              msg: '加购成功',
              result: obj.goodsId + '&' + obj.selectedId + '&' + obj.selectedNum
            })
          } else {
            res.json({
              code: 200,
              status: -1,
              msg: '加购失败',
              result: null
            })
          }
        })
      } else {
        // 添加
        Cartinfo.insertMany({ ...obj, cartid: `${oUser.userid}#${obj.goodsId}#${obj.selectedId}` }).then(addres => {
          if (addres.length > 0) {
            res.json({
              code: 200,
              status: 0,
              msg: '加购成功',
              result: obj.goodsId + '&' + obj.selectedId + '&' + obj.selectedNum
            })
          } else {
            res.json({
              code: 200,
              status: -1,
              msg: '加购失败',
              result: null
            })
          }
        })
      }
    })
  })
})


/**
 * @api {post} /hybrid/uni/cart 获取购物车数据接口
 * @apiDescription 获取购物车数据接口
 * @apiGroup cart
 * @apiName cart
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "获取购物车数据成功",
    result: 购物车Array
   })
 * @apiSampleRequest /uni/cart
 * @apiVersion 1.0.0
 */
router.post('/cart', (req, res) => {
  Cartinfo.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).then(result => {
    res.json({
      code: 200,
      status: 0,
      msg: '购物车数据',
      result
    })
  })
})


/**
 * @api {post} /hybrid/uni/addsub 购物车加减接口
 * @apiDescription 购物车加减接口
 * @apiGroup cart
 * @apiName addsub
 * @apiParam goodsId 商品id
 * @apiParam selectedId 选择属性
 * @apiParam selectedNum 加减之后的数量
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "购物车加减成功",
    result: 1
   })
 * @apiSampleRequest /uni/addsub
 * @apiVersion 1.0.0
 */
router.post('/addsub', (req, res) => {
  const item = req.body.item
  Cartinfo.findOne({ userid: oUser.userid, goodsId: item.goodsId, selectedId: item.selectedId }, { _id: 0, __v: 0 }).then(result => {
    // console.log(result)
    if (result) {
      Cartinfo.updateOne({ userid: result.userid, goodsId: result.goodsId, selectedId: result.selectedId }, {
        $set: {
          selectedNum: item.selectedNum
        }
      }).then(updateres => {
        // {n: 1, nModified: 1, ok: 1 }
        if (updateres.nModified === 1) {
          res.json({
            code: 200,
            status: 0,
            msg: 'add&sub',
            result: null
          })
        }
      })
    }
  })
})


/**
 * @api {post} /hybrid/uni/cart-delete 购物车删除接口
 * @apiDescription 购物车删除接口
 * @apiGroup cart
 * @apiName cart-delete
 * @apiParam goodsId 商品id
 * @apiParam selectedId 选择属性
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "购物车删除成功",
    result: 1
   })
 * @apiSampleRequest /uni/cart-delete
 * @apiVersion 1.0.0
 */
router.post('/cart-delete', (req, res) => {
  const cartid = req.body.cartid
  Cartinfo.deleteOne({ cartid }).then(delete_res => {
    // {n: 1, nModified: 1, ok: 1 }
    if (delete_res.deletedCount === 1) {
      res.json({
        code: 200,
        status: 0,
        msg: '已删除单条数据',
        result: delete_res.deletedCount
      })
    }
  })

})

// 
/**
 * @api {post} /hybrid/uni/cart-deleteall 购物车删除全部接口
 * @apiDescription 购物车删除全部接口 -清空
 * @apiGroup cart
 * @apiName cart-deleteall
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "购物车删除全部成功",
    result: 1
   })
 * @apiSampleRequest /uni/cart-deleteall
 * @apiVersion 1.0.0
 */
router.post('/cart-deleteall', (req, res) => {
  Cartinfo.deleteMany({ cartid: { $in: req.body } }).then(one => {
    res.json({
      code: 200,
      status: 0,
      msg: '删除选中成功',
      result: one
    })
  })
})


router.put('/set-collections', (req, res) => {
  console.log(req.body)
  const { goods_id, isCollect } = req.body;
  // $符号是mongodb中的占位符，也就是说当我们指定一个位置或匹配到一个元素之后，这个符号会自动指向平级的元素来进行操作
  // upsert:true:如果要更新的文档不存在的话会插入一条新的记录
  // $push是直接向数组中进行添加，如果不想添加重复的元素，可以选择使用$addToSet
  // $addToSet 可以给嵌套结构中文档的array中添加对象
  // $pull则是删除内嵌数组中的某一元素
  if (!isCollect) {
    Vuer.findOneAndUpdate({ userid: oUser.userid }, {
      $addToSet: {
        collections: goods_id
      }
    }, {
      upsert: true
    }).then(response => {
      // console.log(response)
      // {n: 1, nModified: 1, ok: 1}
      res.json({
        code: 200,
        status: 0,
        msg: '收藏成功',
        result: response
      })
    })
  } else {
    Vuer.findOneAndUpdate({ userid: oUser.userid }, {
      $pull: {
        collections: goods_id
      }
    }).then(response => {
      // console.log(response)
      // {n: 1, nModified: 1, ok: 1}
      res.json({
        code: 200,
        status: 0,
        msg: '取消收藏成功',
        result: response
      })
    })
  }
})


router.put('/add-history', (req, res) => {
  // $addToSet 可以给嵌套结构中文档的array中添加对象
  Vuer.findOneAndUpdate({ userid: oUser.userid }, {
    $addToSet: {
      history: req.body._id
    }
  }, {
    upsert: true
  }).then(response => {
    // {n: 1, nModified: 1, ok: 1}
    res.json({
      code: 200,
      status: 0,
      msg: '增加浏览历史记录',
      result: response
    })
  })
})

router.post('/add-couponse-code', (req, res) => {
  // $addToSet 可以给嵌套结构中文档的array中添加对象
  Vuer.findOneAndUpdate({ userid: oUser.userid }, {
    $addToSet: {
      coupons: req.body.code + "#" + Date.now() + "#" + oUser.userid
    }
  }, {
    upsert: true
  }).then(response => {
    // {n: 1, nModified: 1, ok: 1}
    res.json({
      code: 200,
      status: 0,
      msg: '增加优惠券记录',
      result: response
    })
  })
})

router.post('/query-of-goodsid', (req, res) => {
  Goodlist.find({ goods_id: { $in: req.body.list } }, { _id: 0, __v: 0 }).then(response => {
    // {n: 1, nModified: 1, ok: 1}
    res.json({
      code: 200,
      status: 0,
      msg: '由id查询商品信息成功',
      result: response
    })
  })
})

/** */
/** */
/** 地址 --------------------------*/
/** */
/** */

/**
 * @api {post} /hybrid/uni/add-area 添加地址接口
 * @apiDescription 添加地址接口
 * @apiGroup Adress
 * @apiName add-area
 * @apiParam req.body.content
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "添加地址成功",
    result: 1
   })
 * @apiSampleRequest /uni/add-area
 * @apiVersion 1.0.0
 */
router.post('/add-area', (req, res) => {
  if (req.body.content.isDefault) {
    Addressinfo.updateMany({ userid: oUser.userid }, {
      $set: {
        // 先全变false
        isDefault: false
      }
    }).then(all => {
      Addressinfo.insertMany({
        userid: oUser.userid,
        ...req.body.content,
        id: `area#${oUser.userid}#${Date.now()}`
      }).then(result => {
        res.json({
          code: 200,
          status: 0,
          msg: '添加地址成功',
          result
        })
      })
    })
  } else {
    Addressinfo.insertMany({
      userid: oUser.userid,
      ...req.body.content,
      id: `area&${oUser.userid}&${Date.now()}`
    }).then(result => {
      res.json({
        code: 200,
        status: 0,
        msg: '添加地址成功',
        result
      })
    })
  }
})


/**
 * @api {post} /hybrid/uni/getarea 获取地址列表接口
 * @apiDescription 获取地址列表接口
 * @apiGroup Adress
 * @apiName getarea
 * @apiParam id 地址id
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "获取地址列表成功",
    result: Array
   })
 * @apiSampleRequest /uni/getarea
 * @apiVersion 1.0.0
 */
router.post('/getarea', (req, res) => {
  Addressinfo.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).then(result => {
    res.json({
      code: 200,
      status: 0,
      msg: '添加地址成功',
      result
    })
  })
})

/**
 * @api {post} /hybrid/uni/modify-area 修改默认接口
 * @apiDescription 修改默认接口
 * @apiGroup Adress
 * @apiName modify-area
 * @apiParam id 地址id
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改默认成功",
    result: Array
   })
 * @apiSampleRequest /uni/modify-area
 * @apiVersion 1.0.0
 */
router.post('/modify-area', (req, res) => {
  Addressinfo.updateMany({ userid: oUser.userid }, {
    $set: {
      // 先全变false
      isDefault: false
    }
  }).then(all => {
    // { n: 2, nModified: 1, ok: 1 }
    Addressinfo.updateOne({ userid: oUser.userid, id: req.body.id }, {
      $set: {
        isDefault: true
      }
    }).then(result => {
      if (result.n) {
        // 获取新值
        Addressinfo.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).then(result2 => {
          res.json({
            code: 200,
            status: 0,
            msg: '修改默认地址成功',
            result: result2
          })
        })
      }
    })
  })
})


/** TODO:???
 * @api {post} /hybrid/uni/modify-area 由id更改modify-item
 * @apiDescription 由id更改modify-item
 * @apiGroup Adress
 * @apiName modify-area
 * @apiParam id 地址id
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "修改成功",
    result: Array
   })
 * @apiSampleRequest /uni/modify-area
 * @apiVersion 1.0.0
 */
router.post('/modify-item', (req, res) => {
  let obj = req.body
  // delete obj.isDefault //不更改原来的默认属性, 此方法返回布尔值(NOTE: 此处改为Dialog选择是否默认)
  if (obj.isDefault) {
    Addressinfo.updateMany({ userid: oUser.userid }, {
      $set: {
        // 先全变false
        isDefault: false
      }
    }).then(all => {
      Addressinfo.updateOne({ userid: oUser.userid, id: obj.id }, {
        $set: {
          ...obj
        }
      }).then(all => {
        if (all.nModified) {
          res.json({
            code: 200,
            status: 0,
            msg: '修改地址成功',
            result: all
          })
        }
      })
    })
  } else {
    Addressinfo.updateOne({ userid: oUser.userid, id: obj.id }, {
      $set: {
        ...obj
      }
    }).then(all => {
      if (all.nModified) {
        res.json({
          code: 200,
          status: 0,
          msg: '修改地址成功',
          result: all
        })
      }
    })
  }
})


/**
 * @api {post} /hybrid/uni/delete-area 删地址
 * @apiDescription 删地址
 * @apiGroup Adress
 * @apiName delete-area
 * @apiParam id 地址id
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "删除成功",
    result: Array
   })
 * @apiSampleRequest /uni/delete-area
 * @apiVersion 1.0.0
 */
router.post('/delete-area', (req, res) => {
  Addressinfo.deleteOne({ userid: oUser.userid, id: req.body.id }).then(one => {
    if (one.deletedCount) {
      Addressinfo.find({ user: req.body.user }, { _id: 0, __v: 0 }).then(result => {
        res.json({
          code: 200,
          status: 0,
          msg: '删除成功',
          result
        })
      })
    }
  })
})

router.post('/delete-select-area', (req, res) => {
  Addressinfo.deleteMany({ id: { $in: req.body } }).then(one => {
    // if (one.deletedCount) {
    // Addressinfo.find({ user: req.body.user }).then(result => {
    res.json({
      code: 200,
      status: 0,
      msg: '删除选中成功',
      result: one
    })
    //   })
    // }
  })
})

/**
 * @api {post} /hybrid/uni/cities 获取城市列表
 * @apiDescription 获取城市列表
 * @apiGroup cities
 * @apiName cities
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "获取成功",
    result: Array
   })
 * @apiSampleRequest /uni/cities
 * @apiVersion 1.0.0
 */
router.get('/cities', (req, res) => {
  Cityinfo.find({}, { _id: 0, __v: 0 }).then(result => {
    if (result.length) {
      res.json({
        code: 200,
        status: 0,
        msg: '获取地址成功',
        result
      })
    }
  })
})



/**
 * @api {post} /hybrid/uni/place-an-order 下单
 * @apiDescription 下单
 * @apiGroup Order
 * @apiName place-an-order
 * @apiParam 6个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /uni/place-an-order
 * @apiVersion 1.0.0
 */
router.post('/place-an-order', (req, res) => {
  const { orderForm, coupon, goods } = req.body;
  Order({ ...req.body, userid: oUser.userid, orderTime: new Date().getTime() }).save().then((result) => {
    // console.log(result)//就是req.body加上_id
    // 删除优惠券记录
    Vuer.findOneAndUpdate({ userid: oUser.userid }, {
      $pull: {
        coupons: coupon.id
      }
    }).then(response1 => {
      // console.log(response1)//{ n: 1, nModified: 1, ok: 1 }
      // 删购物车记录(从购物车下单才需要删除记录)
      if (orderForm === 'list') {
        // let delcartoforder = goods.map(item => item.cartid)
        // console.log(delcartoforder)
        Cartinfo.deleteMany({ cartid: { $in: goods.map(item => item.cartid) } }).then(response2 => {
          // console.log(response2)//{ n: 2, ok: 1, deletedCount: 2 }
          res.json({
            code: 200,
            status: 0,
            msg: '下单成功,优惠券和购物车记录已删除',
            result: response2
          })
        })
      } else {
        res.json({
          code: 200,
          status: 0,
          msg: '下单成功,优惠券记录已删除',
          result: response1
        })
      }
    })
  })
})

/**
 * @api {post} /hybrid/uni/get-orders 获取订单
 * @apiDescription 获取订单
 * @apiGroup Order
 * @apiName get-orders
 * @apiParam 6个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /uni/get-orders
 * @apiVersion 1.0.0
 */
router.post('/get-orders', (req, res) => {
  Order.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).sort({ 'orderTime': -1 }).then((result) => {
    res.json({
      code: 200,
      status: 0,
      msg: '获取订单列表',
      result
    })
  })
})


/**
 * @api {post} /hybrid/uni/del-orders 删除订单
 * @apiDescription 删除订单
 * @apiGroup Order
 * @apiName del-orders
 * @apiParam 6个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /uni/del-orders
 * @apiVersion 1.0.0
 */
router.post('/del-orders', (req, res) => {
  Order.deleteOne({ userid: oUser.userid, orderID: req.body.orderID }).then((response) => {
    Order.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).sort({ 'orderTime': -1 }).then((result) => {
      res.json({
        code: 200,
        status: 0,
        msg: '删除订单',
        result
      })
    })
  })
})


/**
 * @api {post} /hybrid/uni/add-orders-evaluate 设置评论
 * @apiDescription 设置评论
 * @apiGroup Order
 * @apiName /add-orders-evaluate
 * @apiParam 6个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /uni/add-orders-evaluate
 * @apiVersion 1.0.0
 */
router.post('/add-orders-evaluate', (req, res) => {
  const { evaluate, orderID, type } = req.body;
  Order.updateOne({ userid: oUser.userid, orderID }, { $set: { evaluate: evaluate, type: type } }).then((response) => {
    Order.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).sort({ 'orderTime': -1 }).then((result) => {
      res.json({
        code: 200,
        status: 0,
        msg: '添加评论',
        result
      })
    })
  })
})

/**
 * @api {post} /hybrid/uni/modify-orders-type 修改type
 * @apiDescription 修改type
 * @apiGroup Order
 * @apiName /modify-orders-type
 * @apiParam 2个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /uni//modify-orders-type
 * @apiVersion 1.0.0
 */
router.post('/modify-orders-type', (req, res) => {
  const { orderID, type } = req.body;
  Order.updateOne({ userid: oUser.userid, orderID }, { $set: { type } }).then((response) => {
    Order.find({ userid: oUser.userid }, { _id: 0, __v: 0 }).sort({ 'orderTime': -1 }).then((result) => {
      res.json({
        code: 200,
        status: 0,
        msg: '修改type类型',
        result: result
      })
    })
  })
})


/**
 * @api {post} /hybrid/uni/modify-logistics 修改物流信息
 * @apiDescription 修改物流信息
 * @apiGroup Order
 * @apiName /modify-logistics
 * @apiParam 3个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /uni/modify-logistics
 * @apiVersion 1.0.0
 */
router.post('/modify-logistics', (req, res) => {
  const { orderID, text, time } = req.body;
  Order.findOneAndUpdate({ userid: oUser.userid, orderID }, {
    $addToSet: {
      logistics: {
        text,
        time
      }
    }
  }, {
    upsert: true,
    new: true,
    select: { _id: 0, __v: 0 }
  }).then(response => {
    res.json({
      code: 200,
      status: 0,
      msg: '添加物流',
      result: response
    })
  })
})

/**
 * @api {post} /hybrid/uni/modify-del-logistics 删除物流信息
 * @apiDescription 删除物流信息
 * @apiGroup Order
 * @apiName modify-del-logistics
 * @apiParam 3个
 * @apiSuccessExample { json } Success-response:
 * res.json({
    code: 200,
    status: 0,
    msg: "xxx",
    result: Array
   })
 * @apiSampleRequest /unimodify-del-logistics
 * @apiVersion 1.0.0
 */
router.post('/modify-del-logistics', (req, res) => {
  const { orderID, text, time } = req.body;
  Order.findOneAndUpdate({ userid: oUser.userid, orderID }, {
    $pull: {
      logistics: {
        text,
        time: time
      }
    }
  }, {
    new: true,
    select: { _id: 0, __v: 0 }
  }).then(response => {
    res.json({
      code: 200,
      status: 0,
      msg: '删除物流',
      result: response
    })
  })
})


module.exports = router;
